const express = require('express');
const mysql = require('mysql2');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const cors = require('cors');
const multer = require('multer');
const path = require('path');

const app = express();
const port = 3000;

// CORS 配置
const corsOptions = {
  origin: 'http://localhost:5173',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  optionsSuccessStatus: 200
};

// 中间件
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 文件上传配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// 数据库连接
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'pet_adoption'
});

db.connect(err => {
  if (err) {
    console.error('数据库连接失败：', err);
    return;
  }
  console.log('数据库连接成功');
});

// JWT 认证中间件
const authenticateToken = (req, res, next) => {
  const token = req.headers['authorization'];

  if (!token) {
    return res.status(403).send('访问被拒绝');
  }

  jwt.verify(token, 'your_jwt_secret', (err, user) => {
    if (err) {
      return res.status(403).send('无效的令牌');
    }
    req.user = user;
    next();
  });
};

// 用户注册
app.post('/register', async (req, res) => {
  const { username, password, email, avatar, phone, gender, address } = req.body;

  if (!username || !password || !email) {
    return res.status(400).json({ error: "用户名、密码和邮箱不能为空" });
  }

  try {
    const [existingUser] = await db.promise().query(
      'SELECT * FROM users WHERE username = ? OR email = ?',
      [username, email]
    );

    if (existingUser.length > 0) {
      return res.status(400).json({ error: "用户名或邮箱已被占用" });
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    await db.promise().query(
      'INSERT INTO users (username, password, email, avatar, phone, gender, address) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [username, hashedPassword, email, avatar || null, phone || null, gender || 0, address || null]
    );

    res.json({ success: true, message: "注册成功" });
  } catch (err) {
    console.error("注册失败:", err);
    res.status(500).json({ error: "服务器错误，注册失败" });
  }
});

// 用户登录
app.post('/login', async (req, res) => {
  const { username, password } = req.body;

  try {
    const [user] = await db.promise().query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );

    if (user.length === 0) {
      return res.status(401).json({ error: "用户名不存在" });
    }

    const isMatch = await bcrypt.compare(password, user[0].password);
    if (!isMatch) {
      return res.status(401).json({ error: "密码错误" });
    }

    const token = jwt.sign({ userId: user[0].id }, 'your_jwt_secret', {
      expiresIn: '1h'
    });

    res.json({
      token,
      user: {
        id: user[0].id,
        username: user[0].username,
        email: user[0].email,
        avatar: user[0].avatar,
        phone: user[0].phone,
        gender: user[0].gender,
        address: user[0].address
      }
    });
  } catch (err) {
    console.error("登录失败:", err);
    res.status(500).json({ error: "服务器错误，登录失败" });
  }
});

// 获取用户资料
app.get('/profile', authenticateToken, async (req, res) => {
  try {
    const [user] = await db.promise().query(
      `SELECT 
        id, 
        username, 
        email, 
        phone, 
        address 
       FROM users 
       WHERE id = ?`,
      [req.user.userId]
    );

    if (user.length === 0) {
      return res.status(404).json({ 
        success: false,
        error: "用户不存在" 
      });
    }

    res.json({
      success: true,
      data: user[0]
    });
  } catch (err) {
    console.error("获取用户信息失败:", err);
    res.status(500).json({ 
      success: false,
      error: "获取用户信息失败" 
    });
  }
});

// 更新用户资料
app.put('/profile', authenticateToken, async (req, res) => {
  const { 
    username, 
    email, 
    phone, 
    address 
  } = req.body;
  
  const userId = req.user.userId;

  if (!username || !email) {
    return res.status(400).json({ 
      success: false,
      error: "用户名和邮箱不能为空" 
    });
  }

  try {
    const [existingUser] = await db.promise().query(
      `SELECT id 
       FROM users 
       WHERE (username = ? OR email = ?) 
       AND id != ?`,
      [username, email, userId]
    );

    if (existingUser.length > 0) {
      return res.status(400).json({ 
        success: false,
        error: "用户名或邮箱已被占用" 
      });
    }

    await db.promise().query(
      `UPDATE users 
       SET 
         username = ?, 
         email = ?, 
         phone = ?, 
         address = ? 
       WHERE id = ?`,
      [
        username, 
        email, 
        phone || null, 
        address || null, 
        userId
      ]
    );

    const [updatedUser] = await db.promise().query(
      `SELECT 
         id, 
         username, 
         email, 
         phone, 
         address 
       FROM users 
       WHERE id = ?`,
      [userId]
    );

    res.json({
      success: true,
      data: updatedUser[0]
    });
  } catch (err) {
    console.error("更新用户资料失败:", err);
    res.status(500).json({ 
      success: false,
      error: "更新用户资料失败" 
    });
  }
});

// 上传头像
app.post('/upload-avatar', authenticateToken, upload.single('avatar'), async (req, res) => {
  try {
    const userId = req.user.userId;
    const avatarUrl = `http://localhost:3000/uploads/${req.file.filename}`;

    await db.promise().query(
      'UPDATE users SET avatar = ? WHERE id = ?',
      [avatarUrl, userId]
    );

    res.json({ avatarUrl });
  } catch (err) {
    console.error("上传头像失败:", err);
    res.status(500).json({ error: "上传头像失败" });
  }
});

// 帖子相关路由
app.get('/posts', async (req, res) => {
  try {
    const [posts] = await db.promise().query(
      'SELECT * FROM posts ORDER BY date DESC'
    );
    res.json(posts);
  } catch (err) {
    console.error("获取帖子失败:", err);
    res.status(500).json({ error: "获取帖子失败" });
  }
});

app.get('/posts/:id', async (req, res) => {
  try {
    const [post] = await db.promise().query(
      'SELECT * FROM posts WHERE id = ?',
      [req.params.id]
    );
    
    if (post.length === 0) {
      return res.status(404).json({ error: "帖子不存在" });
    }
    
    res.json(post[0]);
  } catch (err) {
    console.error("获取帖子详情失败:", err);
    res.status(500).json({ error: "获取帖子详情失败" });
  }
});

app.post('/posts', authenticateToken, async (req, res) => {
  const { title, content } = req.body;
  
  if (!title || !content) {
    return res.status(400).json({ error: "标题和内容不能为空" });
  }

  try {
    const [user] = await db.promise().query(
      'SELECT username FROM users WHERE id = ?',
      [req.user.userId]
    );
    
    if (user.length === 0) {
      return res.status(404).json({ error: "用户不存在" });
    }

    const result = await db.promise().query(
      'INSERT INTO posts (title, content, author, date, likes, comments) VALUES (?, ?, ?, NOW(), 0, 0)',
      [title, content, user[0].username]
    );
    
    const newPostId = result[0].insertId;
    const [newPost] = await db.promise().query(
      'SELECT * FROM posts WHERE id = ?',
      [newPostId]
    );
    
    res.status(201).json(newPost[0]);
  } catch (err) {
    console.error("创建帖子失败:", err);
    res.status(500).json({ error: "创建帖子失败" });
  }
});

app.delete('/posts/:id', authenticateToken, async (req, res) => {
  try {
    const [post] = await db.promise().query(
      'SELECT * FROM posts WHERE id = ?',
      [req.params.id]
    );
    
    if (post.length === 0) {
      return res.status(404).json({ error: "帖子不存在" });
    }
    
    const [user] = await db.promise().query(
      'SELECT username FROM users WHERE id = ?',
      [req.user.userId]
    );
    
    if (user.length === 0 || user[0].username !== post[0].author) {
      return res.status(403).json({ error: "无权删除此帖子" });
    }
    
    await db.promise().query(
      'DELETE FROM posts WHERE id = ?',
      [req.params.id]
    );
    
    res.json({ success: true, message: "帖子删除成功" });
  } catch (err) {
    console.error("删除帖子失败:", err);
    res.status(500).json({ error: "删除帖子失败" });
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});

// 添加挂失宠物
// 获取挂失列表时包含权限信息
app.get('/api/lost-pets', authenticateToken, async (req, res) => {
  try {
    // 获取所有未找到的挂失记录（公开可见）
    const [pets] = await db.promise().query(
      `SELECT 
        lp.*,
        (lp.user_id = ?) AS can_edit  -- 添加权限标识
       FROM lost_pets lp
       WHERE lp.is_found = 0
       ORDER BY lp.date DESC`,
      [req.user.userId]
    );
    res.json(pets);
  } catch (err) {
    console.error("获取挂失宠物列表失败:", err);
    res.status(500).json({ error: "获取挂失宠物列表失败" });
  }
});

// 获取挂失列表时增加 is_found 条件
app.get('/api/lost-pets', authenticateToken, async (req, res) => {
  try {
    const [pets] = await db.promise().query(
      'SELECT * FROM lost_pets WHERE user_id = ? AND is_found = 0 ORDER BY date DESC',
      [req.user.userId]
    );
    res.json(pets);
  } catch (err) {
    console.error("获取挂失宠物列表失败:", err);
    res.status(500).json({ error: "获取挂失宠物列表失败" });
  }
});

// 标记为已找到改为更新操作
app.patch('/api/lost-pets/:id/found', authenticateToken, async (req, res) => {
  try {
    await db.promise().query(
      'UPDATE lost_pets SET is_found = 1 WHERE id = ? AND user_id = ?',
      [req.params.id, req.user.userId]
    );
    res.json({ success: true });
  } catch (err) {
    console.error("标记失败:", err);
    res.status(500).json({ error: "标记失败" });
  }
});

// 删除/标记为已找到
app.delete('/api/lost-pets/:id', authenticateToken, async (req, res) => {
  try {
    const [pet] = await db.promise().query(
      'SELECT user_id FROM lost_pets WHERE id = ?',
      [req.params.id]
    );
    
    if (pet.length === 0) {
      return res.status(404).json({ error: "挂失记录不存在" });
    }
    
    if (pet[0].user_id !== req.user.userId) {
      return res.status(403).json({ error: "无权操作此记录" });
    }
    
    await db.promise().query(
      'DELETE FROM lost_pets WHERE id = ?',
      [req.params.id]
    );
    
    res.json({ success: true, message: "操作成功" });
  } catch (err) {
    console.error("操作失败:", err);
    res.status(500).json({ error: "操作失败" });
  }
});
